package com.ojoin.ojoin.eb_spider.service.catchdata;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.domain.AssistCatchData;
import com.ojoin.ojoin.eb_spider.service.WebDriverService;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.DownloadUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.NumberUtils;
import com.ojoin.trade.common.utils.URLUtils;
import com.ojoin.trade.common.utils.WaitUtil;
import com.ojoin.trade.common.utils.excel.Excel2003Writer;
import com.ojoin.trade.common.utils.excel.Excel2007WriterImpl;
import com.ojoin.trade.common.utils.excel.ExcelReaderUtil;
import com.ojoin.trade.common.utils.excel.IRowReader;
import com.ojoin.trade.supplyloan_core.web.domain.CatchDataStartMessage;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyInventory;

@Service
public class SupplierSUNING_MDDataCatchServiceImpl extends
		SUNINGBaseDataCatchServiceImpl {

	private static Logger log = LoggerFactory
			.getLogger(SupplierSUNING_MDDataCatchServiceImpl.class);

	/**
	 * 消单文件放在D盘vecodes下，文件名为vecodes
	 */

	// 获取付款单

	@Override
	public void catchData(AssistCatchData assistCatchData) throws Exception {
		super.init(assistCatchData);

		try {
			prepareCatchData();

			boolean flag = isLoginSuccess();

			if (flag) {
				// getOrderOut();
				// recode();
				//vecodes();
				
				 Set<String> set = readExce();
				 vecodes(set);
				 //vecodes();
			}

			// TODO

		} catch (Exception e) {
			LogUtils.error(log, e.toString());
			throw e;

		} finally {

		}
	}

	public static void main(String[] args) throws IOException {
		// SupplierSUNING_MDDataCatchServiceImpl sm = new
		// SupplierSUNING_MDDataCatchServiceImpl();
		// Set<String> set = sm.readExce();
		// System.out.println(set);

		// writeToTxt("oms1","code");
		// writeToTxt("oms2","code");
		// Excel2003Writer.writeExcel("D:\\vecodes\\code.xls");

		List<List<String>> list = new ArrayList<List<String>>();

		List<String> li = new ArrayList<String>();

		li.add("oms");
		li.add("code");

		List<String> li1 = new ArrayList<String>();

		li1.add("oms1");
		li1.add("code1");

		list.add(li);
		list.add(li1);

		Excel2003Writer.writeExcelAppend("D:\\vecodes\\code.xls", list);
	}

	@Override
	public boolean isLoginSuccess() throws Exception {
		boolean loginflag = false;

		String username = this.getAssistCatchData().getStartMess().getPlatformUser().getUsername();
		String password = this.getAssistCatchData().getStartMess().getPlatformUser().getPassword();

		String loginUrl = this.getAssistCatchData().getStartMess().getPlatformInfo().getLoginUrl();

		loginflag = LoginByUserInfo(loginUrl, username, password);

		return loginflag;
	}

	public void recode() throws Exception {

		try {
			// String url =
			// "http://scs.suning.com/sps/portal/showPortalPage.action";

			this.getWebDriver().click("id", "SCSA00001");
			this.getWebDriver().click("css",
					"#ulAllMenus > li:nth-child(5) > a");

			this.getWebDriver().click(WebDriverService.xpath,
					"//*[@id=\"100000159\"]/a");
			// this.getWebDriver().get(url);

			this.getWebDriver().switchToframe("frameBody");

			this.getWebDriver().click("css", "#ulreturn > li:nth-child(5) > a");
			String starttime = "2014-12-01";
			String endtime = "2014-12-31";

			List<Map<String, String>> Timeli = getTimes(starttime, endtime, 30);

			Iterator<Map<String, String>> it = Timeli.iterator();

			while (it.hasNext()) {
				Map<String, String> timeMap = it.next();

				String stime = timeMap.get("stime");
				String etime = timeMap.get("etime");

				this.getWebDriver().sendKeys("id", "saleOrderDate1", stime);

				this.getWebDriver().sendKeys("id", "saleOrderDate2", etime);

				this.getWebDriver().selectByValue("id", "orderStatus", "40");
				this.getWebDriver()
						.click("css",
								"#SearchFrm > table > tbody > tr:nth-child(3) > td:nth-child(5) > a");

				List<WebElement> li = this
						.getWebDriver()
						.findElements(
								"css",
								"body > div.tabs > div:nth-child(3) > div > div.tabs-contain > div > div:nth-child(2)");

				if (!CommonUtils.isEmpty(li)) {
					Iterator<WebElement> its = li.iterator();
					while (its.hasNext()) {
						WebElement web = its.next();

						String oms = this
								.getWebDriver()
								.getText(web, "css",
										"div > div > div.itemTop > div.orderNum > span:nth-child(2)");

						oms = oms.split("：")[1];

						vecode(oms);

						// this.getWebDriver().click(web, "css",
						// "table > tbody > tr > td.item-goodsI .itemInner a");

					}
				}
			}

		} catch (Exception e) {
			LogUtils.info(log, e.getMessage());
		}

	}

	public void vecodes() {
		List<String> li = new ArrayList<String>();
		// li.add("00017083480401");
		//li.add("00017083474501");
		li.add("00025831279201");
		// li.add("00014533706401");

		Iterator<String> it = li.iterator();
		while (it.hasNext()) {
			String oms = it.next();
			try {
				vecode(oms);
			} catch (Exception e) {
				LogUtils.info(log, e.toString());
			}

		}
	}
	
	public void vecodes(Set<String> set) {
		

		Iterator<String> it = set.iterator();
		while (it.hasNext()) {
			String oms = it.next();
			try {
				vecode(oms);
			} catch (Exception e) {
				LogUtils.info(log, e.toString());
			}

		}
	}
	

	public String getCookies() {
		// 验证码破解
		StringBuffer sb = new StringBuffer();
		Set<Cookie> cookies = this.getWebDriver().getDriver().manage()
				.getCookies();
		if (!CommonUtils.isEmpty(cookies)) {

			Iterator<Cookie> it = cookies.iterator();
			while (it.hasNext()) {
				Cookie co = it.next();
				sb.append(co.getName() + "=" + co.getValue() + ";");
			}
		}

		return sb.toString();
	}

	public void vecode(String oms) throws Exception {
		String url = "http://scs.suning.com/sps/saleOrder/updateConfirmReceipt.action?omsOrderItemNo="
				+ oms + "&iunik=";

		boolean flag = true;
		int count = 0;
		while (flag) {
			String code = "";
			if (count < 10) {
				code = "000" + count;
			} else if (10 <= count && count < 100) {
				code = "00" + count;
			} else if (100 <= count && count < 1000) {
				code = "0" + count;
			} else {
				code = "" + count;
			}

			count++;

			/*
			 * this.getWebDriver().get(url+code); String text =
			 * this.getWebDriver().getText("css", "body > pre");
			 */
			String text = URLUtils.getJsonByUrl(getCookies(), url + code);

			WaitUtil.waitTimes(300);

			if (!CommonUtils.isEmpty(text) && text.contains("校验码输入错误")) {
				if (count % 100 == 0) {
					LogUtils.info(log, "oms --- [%s ]校验码输入错误--[%s]", oms, code);
					// WaitUtil.waitTimeSeconds(5);
				}

			}else if(text.contains("订单不是厂家已发货状态")){
				LogUtils.info(log, "oms --- [%s ]已消单", oms);
				break;
			}else {
				LogUtils.info(log, "oms --- [%s ]校验码输入正确--[%s] , text-- [%s]", oms, code,text);
				List<List<String>> list = new ArrayList<List<String>>();

				List<String> li = new ArrayList<String>();

				li.add(oms);
				li.add(code);

				list.add(li);
				
				Excel2003Writer.writeExcelAppend("D:\\vecodes\\code.xls", list);
				
				break;
			}
		}

	}

	public static void writeToTxt(String oms, String code) throws IOException {
		File file = new File("D:\\vecodes\\vecodes_code.txt");

		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			fw = new FileWriter(file, true);
			bw = new BufferedWriter(fw);
			bw.append(oms + "___" + code + "\r\n");
			bw.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (null != bw) {
				bw.close();
			}
		}

	}

	public Set<String> readExce() {
		File file = new File("D:\\vecodes\\vecodes.xlsx");
		Set<String> set = new HashSet<String>();
		FileInputStream in;
		try {
			in = new FileInputStream(file);

			IRowReader reader = gerIRowReader(set);

			ExcelReaderUtil.readExcel(reader, in);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return set;

	}

	public IRowReader gerIRowReader(final Set<String> set) {
		IRowReader reader = new IRowReader() {

			public void getRows(int sheetIndex, String sheetName, int curRow,
					List<String> rowlist) {
				// 总库存金额

				String oms = rowlist.get(0);

				set.add(oms);
			}
		};

		return reader;
	}

	public void getOrderOut() throws Exception {
		// 送货记录
		// 对账单

		String starttime = "2013-06-01";
		String endtime = "2014-01-11";
		List<Map<String, String>> Timeli = getTimes(starttime, endtime, 6);

		Iterator<Map<String, String>> it = Timeli.iterator();
		while (it.hasNext()) {
			Map<String, String> timeMap = it.next();

			String stime = timeMap.get("stime");
			String etime = timeMap.get("etime");
			this.getWebDriver()
					.get("http://scs.suning.com/sps/rtOrderReport/queryReport.action?menuid=100000098&scspageexptime=1463537326087");

			this.getWebDriver().sendKeys("id", "puteEnddate1", stime);

			this.getWebDriver().sendKeys("id", "puteEnddate2", etime);

			this.getWebDriver().click("id", "orderCode");
			this.getWebDriver().click("id", "buyerProductcode");

			this.getWebDriver().click("css", "#check  span");

			boolean exit = this.getWebDriver()
					.IsExist("css", "#download  span");

			if (!exit) {
				continue;
			}

			this.getWebDriver().click("css", "#download  span");

			File payment = null;

			File downloadFileDir = new File(this.getAssistCatchData().getDownloadDir());

			payment = DownloadUtils.waitFileDownloadOver(downloadFileDir,
					"^ORDERRETURN.*.csv$");

			LogUtils.info(log, "文件名为：" + payment.getAbsolutePath() + "-->文件大小："
					+ payment.length() / 1024 + "kb");

			renameFile(payment, payment.getParent() + File.separator + stime
					+ "--" + etime + ".csv");

		}

	}

	public void renameFile(File toBeRenamed, String toFile) {

		File newFile = new File(toFile);

		// 修改文件名
		if (toBeRenamed.renameTo(newFile)) {
			LogUtils.info(log, "File has been renamed.");
		} else {
			LogUtils.info(log, "Error renameing file");
		}

	}

	@Override
	public boolean getUnpayAccountData() throws BusinessException, IOException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean getPayAccountData() throws BusinessException, Exception {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean getOutstoreOrderData() throws BusinessException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean getInstoreOrderData() throws IOException {
		// TODO Auto-generated method stub
		return false;
	}

}
